/*
 * @Descripttion: 
 * @version: 
 * @Author: zhengys
 * @Date: 2020-12-14 21:09:18
 * @LastEditors: zhengys
 * @LastEditTime: 2021-02-27 16:08:05
 */


const http = require('http');  // 加载http服务模块
const fs = require('fs');
const path = require('path');
const url = require('url');
const common = require('./moudle/common');

http.createServer(function (req, res) {
  // http://127.0.0.1:3000/login.html

  // 1. 获取地址
  let pathName = url.parse(req.url).pathname;
  pathName = pathName == '/' ? '/index.html' : pathName;
  
  // 获取后缀名 path.extname();
  let extname = path.extname(pathName)
  
  // 2. 通过fs模块读取文件
  if(pathName != '/favicon.ico'){
    fs.readFile(`./static${pathName}`,(err,data) => {
      if(err){
        fs.readFile('./static/404.html',(err,data404)=>{
          if(err){
            console.log('404')
          }else{
            res.writeHead(404, {'Content-Type': 'text/html;charset="utf-8"'});
            res.end(data404);
          }
        })
      }else{
        let mime = common.getFileMime(extname) // 根据对应的后缀名，获取对应的文件格式
        res.writeHead(200, {'Content-Type': `${mime};charset="utf-8"`});
        res.end(data);
      }
    })
  }
}).listen(3000);

console.log('Server running at http://127.0.0.1:3000/');